#include "ShadowEffect.h"

ShadowEffect::ShadowEffect(const LPDIRECT3DDEVICE9 device, EffectManager *effMgr, TextureManager *texMgr) :Effect(device, effMgr, texMgr)
{
	texMgr->makeRenderTarget(L"shadowMap", TextureManager::DEPTH_RT_FORMAT, TextureManager::SHADOW_MAP_SIZE, TextureManager::SHADOW_MAP_SIZE);
}

ShadowEffect::~ShadowEffect(void)
{
}

void ShadowEffect::runEffect()
{
}

void ShadowEffect::renderDepthBuffer(Camera *camera, SpotLight *light, vector<ModelMesh *> meshes, LPDIRECT3DSURFACE9 prevSurf)
{
	device->SetRenderTarget(0, *texMgr->getSurface(L"shadowMap"));
	device->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_RGBA(0,0,0, 0), 1.0f, 0);

	effMgr->setupEffect(SHADOW_RENDER_FX);
	D3DXHANDLE handle = effMgr->getSetEffect()->GetTechniqueByName("ShadowMap");
	effMgr->getSetEffect()->SetTechnique(handle);

	D3DXMATRIX matWorld;
	D3DXMatrixIdentity(&matWorld);

	effMgr->getSetEffect()->SetVector("xLightPos", &light->getPosition4());
	effMgr->getSetEffect()->SetFloat("xLightPower", 2.0f);
	effMgr->getSetEffect()->SetFloat("xAmbient", 1.0f);

	device->BeginScene();
	effMgr->getSetEffect()->Begin(NULL, 0);
	vector<ModelMesh *>::const_iterator itr;
	for(itr = meshes.begin();  itr != meshes.end(); itr++) 
	{
		ModelMesh *mesh = (ModelMesh *)*itr;
		effMgr->getSetEffect()->SetMatrix("xWorld", &mesh->getWorld());
		effMgr->getSetEffect()->SetMatrix("xWorldViewProjection", &(mesh->getWorld() * camera->getViewProjMatrix()));
		effMgr->getSetEffect()->SetMatrix("xLightsWorldViewProjection", &(mesh->getWorld() * light->getViewProjMatrix()));
		//TODO: do we need to multiply world
		effMgr->getSetEffect()->BeginPass(0);
		mesh->getMesh()->DrawSubset(0);
		effMgr->getSetEffect()->EndPass();
	}
	effMgr->getSetEffect()->End();
	device->EndScene();

	device->SetRenderTarget(0, prevSurf);
}